package com.ebupt.migu.music.roster.service.impl;

import cn.hutool.json.JSONUtil;
import com.ebupt.migu.music.api.util.CacheTask;
import com.ebupt.migu.music.common.constants.RedidKeyConstant;
import com.ebupt.migu.music.common.entity.Page;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.roster.entity.RosterBlackEntity;
import com.ebupt.migu.music.roster.entity.RosterWhiteEntity;
import com.ebupt.migu.music.roster.mapper.RosterMapper;
import com.ebupt.migu.music.roster.service.RosterService;
import com.ebupt.migu.music.roster.utils.ESutils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2020/3/26
 */
@Slf4j
@Service
public class RosterServiceImpl implements RosterService {

    @Autowired
    private ESutils eSutils;
    @Autowired
    private RosterMapper rosterMapper;
    @Resource
    protected RedisTemplate redisTemplate;
    /**
     * 创建黑白名单
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject add(Map<String, Object> params) {
        ResultObject res = new ResultObject();
        // 验证同名
        if (rosterMapper.isRosterNameExist(params)) {
            res.setCode(StatusEnum.ROSTER_NAME_EXIST.getCode());
            res.setMsg(StatusEnum.ROSTER_NAME_EXIST.getMsg());
            return res;
        }
        // 创建黑白名单分组,并获取分组ID
        rosterMapper.addRoster(params);
        int roster_id = Integer.valueOf(String.valueOf(params.get("id")));
        // mode： 1-手动填写； 2-文件上传；
        String mode = params.get("mode").toString();
        if ("1".equals(mode)) {
            Map<String, Object> map = new HashMap<>();
            map.putAll(params);
            inverse(params, String.valueOf(roster_id));
            map.put("status", "1");
            map.put("id", roster_id);
            // 更新名单状态为已完成
            rosterMapper.updateRosterStatusByRosterID(map);
        }
        updateCache();
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        return res;
    }

    /**
     * 追加黑白名单
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject append(Map<String, Object> params) {
        ResultObject res = new ResultObject();
        // 追加方式： 1-手动追加单个用户； 2-文件上传方式追加；
        String mode = params.get("mode").toString();
        String roster_id = params.get("rosterId").toString();
        if ("1".equals(mode)) {
            inverse(params, roster_id);
        }
        if ("2".equals(mode)) {
            rosterMapper.rosterExtend(params);
        }
        updateCache();
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        return res;
    }

    /**
     * 条件、分页查询名单列表
     * <p> 名单类型：1- 白名单; 2- 黑名单;
     * 1、用户手机号
     * 2、用户UID
     * 3、名单名称
     * 4、创建人
     * 5、创建人部门
     * 6、创建时间区间
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject rosterList(Map<String, Object> params) {
        ResultObject<Page<HashMap<String, Object>>> res = new ResultObject<>();
        if ("1".equals(params.get("isAdmin"))) {
            // 超级管理员有权查询所有审批列表
            params.remove("creatorId");
            params.remove("creatorDepartment");
        } else {
            params.remove("cDepartment");
        }
        // 总数
        Integer total = rosterMapper.rosterListCount(params);
        // 分页查询结果集
        List<HashMap<String, Object>> datas = rosterMapper.rosterList(params);
        // 分页
        Page<HashMap<String, Object>> page = new Page<>();
        page.setTotal(total);
        page.setData(datas);
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        res.setData(page);
        return res;
    }

    /**
     * 查询名单明细
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject rosterDetail(Map<String, Object> params) {
        ResultObject<Page<HashMap<String, Object>>> res = new ResultObject<>();
        // 总数
        Integer total = rosterMapper.detailsCount(params);
        // 分页查询结果集
        List<HashMap<String, Object>> datas = rosterMapper.details(params);
        // 手机号过敏处理
        if (datas.size() > 0) {
            datas.forEach(data -> {
                data.put("msisdn", phoneMask(data.get("msisdn").toString()));
            });
        }
        // 分页
        Page<HashMap<String, Object>> page = new Page<>();
        page.setTotal(total);
        page.setData(datas);
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        res.setData(page);
        return res;
    }

    /**
     * 手机号脱敏处理
     *
     * @param mobile 手机号
     * @return 脱敏后的手机号
     */
    public static String phoneMask(String mobile) {
        String res = "******";
        if (StringUtils.hasText(mobile)) {
            StringBuilder sb = new StringBuilder(mobile);
            res = sb.replace(2, 8, "******").toString();
        }
        return res;
    }

    /**
     * 删除指定名单分组
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject delete(Map<String, Object> params) {
        ResultObject res = new ResultObject();
        int id = Integer.valueOf(params.get("id").toString());
        // 删除名单分组
        rosterMapper.deleteRoster(id);
        rosterMapper.deleteRosterDetails(id);
        rosterMapper.deleteRosterExtends(id);
        updateCache();
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        return res;
    }

    /**
     * 删除名单内指定成员
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject deleteSingle(Map<String, Object> params) {
        ResultObject res = new ResultObject();
        int id = Integer.valueOf(params.get("id").toString());
        rosterMapper.deleteRosterDetailsForSingle(id);
        res.setCode(StatusEnum.SUCCESS.getCode());
        res.setMsg(StatusEnum.SUCCESS.getMsg());
        updateCache();
        return res;
    }

    /**
     * 手动输入-反查并写入详情
     *
     * @param params
     * @param roster_id
     */
    private void inverse(Map<String, Object> params, String roster_id) {
        Map<String, Object> info = new HashMap<>();
        String memberType = params.get("memberType").toString();
        String paramValue = "";
        if ("1".equals(memberType)) {
            paramValue = String.valueOf(params.get("msisdn"));
//            info = eSutils.inverse_search(params.get("msisdn").toString(), memberType);
        }
        if ("2".equals(memberType)) {
            paramValue = String.valueOf(params.get("uuid"));
//            info = eSutils.inverse_search(params.get("uuid").toString(), memberType);
        }
        // 不追加重复数据
        Map<String, String> map = new HashMap<>();
        map.put("rosterId", roster_id);
        map.put("paramValue", paramValue);
        if (!rosterMapper.isUuidOrMsisdnExist(map)) {
            info = eSutils.inverse_search(paramValue, memberType);
//            info.putAll(params);
            info.put("name", params.get("name"));
            info.put("desc", params.get("desc"));
            info.put("rosterId", roster_id);
            log.info("创建反查结果：{}", info);
            rosterMapper.addRosterInfo(info);
        }

    }


    /**
     * 更新缓存
     */
    protected void updateCache(){
        List<RosterBlackEntity>  rosterBlackEntityList = rosterMapper.getBlackListAll();
        Map<Long, List<RosterBlackEntity>>  blackListMap = rosterBlackEntityList.stream().collect(Collectors.groupingBy(RosterBlackEntity::getRosterId));
        //存储
        redisTemplate.delete(RedidKeyConstant.BLACK_LIST_REDIS_KEY);
        blackListMap.forEach((key,value)->{
            redisTemplate.opsForHash().put(RedidKeyConstant.BLACK_LIST_REDIS_KEY,String.valueOf(key), JSONUtil.toJsonStr(value));
        });
        redisTemplate.boundValueOps(RedidKeyConstant.BLACK_LIST_REDIS_KEY).expire(CacheTask.cacheTime, TimeUnit.MILLISECONDS);
        List<RosterWhiteEntity>  rosterWhiteEntityList = rosterMapper.getWhiteListAll();
        Map<Long, List<RosterWhiteEntity>> whiteListMap = rosterWhiteEntityList.stream().collect(Collectors.groupingBy(RosterWhiteEntity::getRosterId));;
        //存储
        redisTemplate.delete(RedidKeyConstant.WHITE_LIST_REDIS_KEY);
        whiteListMap.forEach((key,value)->{
            redisTemplate.opsForHash().put(RedidKeyConstant.WHITE_LIST_REDIS_KEY, String.valueOf(key), JSONUtil.toJsonStr(value));
        });
        redisTemplate.boundValueOps(RedidKeyConstant.WHITE_LIST_REDIS_KEY).expire(CacheTask.cacheTime, TimeUnit.MILLISECONDS);
    }



}
